#!/bin/bash
# Soft-update safety for Electron mains that predate wavBase64 / uniqueMirror
# (protocol 1 returns only a sandboxed file:// wavPath).
#
# After a successful gen, mirror the WAV into <modelDir>/_out/<ts>-<size>.wav
# and write <modelDir>/_out/.latest so the CDN SDK can fetch a per-job path
# via meshmodel:// without reading shared _last_out.wav.
#
# Line 4 of .latest echoes mesh.job_nonce (or seed=N) so the SDK can prove
# the mirror belongs to *this* generate — a SHA alone cannot.
#
# Installed as audiocpp-host with the real binary beside it as audiocpp-host.bin.
# Published on the CDN as audiocpp-host.wrap.sh (never as the Mach-O/ELF itself).
set -euo pipefail
DIR="$(cd "$(dirname "$0")" && pwd)"
REAL="${DIR}/audiocpp-host.bin"
if [[ ! -x "$REAL" ]]; then
  echo "audiocpp-host.bin missing next to wrapper ($REAL)" >&2
  exit 127
fi

MODEL=""
OUT=""
NONCE=""
prev=""
for a in "$@"; do
  if [[ "$prev" == "--model" ]]; then MODEL="$a"; fi
  if [[ "$prev" == "--out" ]]; then OUT="$a"; fi
  if [[ "$prev" == "--request-option" ]]; then
    case "$a" in
      mesh.job_nonce=*) NONCE="${a#mesh.job_nonce=}" ;;
      seed=*)
        if [[ -z "$NONCE" ]]; then NONCE="seed:${a#seed=}"; fi
        ;;
    esac
  fi
  prev="$a"
done

set +e
"$REAL" "$@"
code=$?
set -e

if [[ "$code" -eq 0 && -n "$MODEL" && -n "$OUT" && -f "$OUT" ]]; then
  size=$(wc -c < "$OUT" | tr -d ' ')
  if [[ "$size" -ge 44 ]]; then
    outdir="${MODEL}/_out"
    mkdir -p "$outdir"
    ts=$(python3 -c 'import time; print(int(time.time()*1000))')
    name="${ts}-${size}.wav"
    cp "$OUT" "${outdir}/${name}"
    # rel, bytes, ts_ms, job_nonce — SDK verifies line 4 before upload.
    printf '%s\n%s\n%s\n%s\n' "_out/${name}" "$size" "$ts" "$NONCE" > "${outdir}/.latest"
    echo "yue2.wav_ready rel=_out/${name} bytes=${size} nonce=${NONCE}" >&2
  fi
fi
exit "$code"
